from typing import List, Dict, Any
from .database_tool import DatabaseTool
from .nlp_tool import NLPTool

class ProductTool:
    def __init__(self, db_tool: DatabaseTool, nlp_tool: NLPTool):
        self.db_tool = db_tool
        self.nlp_tool = nlp_tool

    def search_products(self, query: str) -> Dict[str, Any]:
        """根据用户查询搜索商品"""
        # 分析用户意图
        intent = self.nlp_tool.analyze_intent(query)
        products = []
        total_found = 0

        try:
            if intent["query_type"] == "price_search":
                min_price = intent["parameters"].get("min_price", 0)
                max_price = intent["parameters"].get("max_price", float("inf"))
                products = self.db_tool.get_products_by_price_range(min_price, max_price)
                
                # 如果没有找到商品，尝试扩大价格范围
                if not products:
                    expanded_min = max(0, min_price - 1000)
                    expanded_max = max_price + 1000
                    products = self.db_tool.get_products_by_price_range(expanded_min, expanded_max)

            elif intent["query_type"] == "category_search":
                category = intent["parameters"].get("category")
                products = self.db_tool.get_products_by_category(category)
                
                # 如果没有找到商品，尝试使用关键词搜索
                if not products:
                    products = self.db_tool.search_products(category)

            else:  # keyword_search
                keyword = intent["parameters"].get("keyword")
                products = self.db_tool.search_products(keyword)
                
                # 如果没有找到商品，返回热门商品
                if not products:
                    products = self.db_tool.get_popular_products(5)

            total_found = len(products)
            # 只返回前5个商品
            products = products[:5]

            # 生成推荐文案
            recommendation_text = self.nlp_tool.generate_recommendation_text(products, query)

            return {
                "success": True,
                "total_found": total_found,
                "products": products,
                "recommendation_text": recommendation_text,
                "intent_analysis": intent
            }

        except Exception as e:
            print(f"搜索商品时出错: {str(e)}")
            return {
                "success": False,
                "error": str(e),
                "total_found": 0,
                "products": [],
                "recommendation_text": "抱歉，搜索过程中出现错误。",
                "intent_analysis": intent
            }

    def get_product_details(self, product_id: int) -> Dict[str, Any]:
        """获取商品详细信息"""
        try:
            product = self.db_tool.get_product_by_id(product_id)
            if not product:
                return {
                    "success": False,
                    "error": "商品不存在"
                }
            return {
                "success": True,
                "product": product
            }
        except Exception as e:
            return {
                "success": False,
                "error": str(e)
            }

    def get_popular_products(self, limit: int = 5) -> Dict[str, Any]:
        """获取热门商品"""
        try:
            products = self.db_tool.get_popular_products(limit)
            return {
                "success": True,
                "products": products
            }
        except Exception as e:
            return {
                "success": False,
                "error": str(e)
            } 